package com.scpii.api.controller.user;

import java.util.List;

import javax.annotation.Resource;

import org.codehaus.jackson.type.TypeReference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.scpii.api.common.Constants;
import com.scpii.api.common.annoation.ActionTypeMethod;
import com.scpii.api.common.base.BaseController;
import com.scpii.api.domain.common.Field;
import com.scpii.api.domain.common.Field.FieldStatus;
import com.scpii.api.domain.common.FieldValues;
import com.scpii.api.domain.content.Resources;
import com.scpii.api.domain.user.UserActions.ActionType;
import com.scpii.api.service.common.FieldService;
import com.scpii.api.service.user.UsersService;
import com.scpii.api.util.FileUtil;
import com.scpii.api.util.JsonUtil;
import com.scpii.api.util.PrincipalUtil;

@Controller
@RequestMapping("/user/register")
public class RegisterController extends BaseController {

	@Resource
	private UsersService usersService;

	@Resource
	private FieldService fieldService;

	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(value = "/field", method = RequestMethod.GET)
	@ResponseBody
	public List<Field> getExpandField() {
		List<Field> fields = fieldService.selectAppExpandField(PrincipalUtil
				.getPrincipal().getAppId(),
				Constants.TABLE_PRIKARY_KEY_START_POSITION.get("USERS"),
				FieldStatus.ADD_REQUIRED_SHOW.getValue());
		return fields;
	}

	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(value = "/complete", method = RequestMethod.POST)
	@ResponseBody
	@ActionTypeMethod(ActionType.USER_REGISTER)
	public Boolean complete(
			@RequestParam(value = "userAvatar", required = false) MultipartFile userAvatar,
			@RequestParam("userAliasName") String userAliasName,
			@RequestParam("fieldValues") String fieldValuesStr) {
		Resources resource = FileUtil.save(userAvatar);
		List<FieldValues> fieldValues = JsonUtil.readValueWithString(
				fieldValuesStr, new TypeReference<List<FieldValues>>() {
				});
		usersService.updateUsers(userAliasName, resource == null ? null
				: resource.getThumbImage(), fieldValues);
		return true;
	}
}
